package com.baoleme.controller;

import com.baoleme.common.Result;
import com.baoleme.entity.ShoppingCart;
import com.baoleme.exceptions.BusinessException;
import com.baoleme.exceptions.enumeration.ResponseEnum;
import com.baoleme.service.ShoppingCartService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wuyunbin
 * @since 2024-09-25
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Resource
    private ShoppingCartService shoppingCartService;

    @GetMapping("list")
    public Result<List<ShoppingCart>> list(String userId) {
        idVerify(userId);
        return Result.success(shoppingCartService.listByUserId(userId));
    }

    @DeleteMapping("clean")
    public Result<Boolean> clean(String userId) {
        idVerify(userId);
        return Result.success(shoppingCartService.removeByUserId(userId));
    }

    @PostMapping("sub")
    public Result<Boolean> sub(@RequestBody List<String> shoppingCartIds) {
        for (String shoppingCartId : shoppingCartIds) {
            idVerify(shoppingCartId);
        }
        return Result.success(shoppingCartService.removeByIds(shoppingCartIds));
    }

    @PostMapping("add")
    public Result<Boolean> add(@RequestBody ShoppingCart shoppingCart) {
        return Result.success(shoppingCartService.save(shoppingCart));
    }

    private void idVerify(String id) {
        try {
            Long.parseLong(id);
        } catch (Exception e) {
            throw new BusinessException(ResponseEnum.ILLEGAL_OPERATION);
        }
    }
}
